<template>
    <div>
        <el-form :inline="true">
            <el-form-item>
                <el-button @click="Add" type="primary" plain style="margin-left: 16px;">增加部门</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="danger" plain @click="delDetp">批量删除</el-button>
            </el-form-item>
            <el-form-item>
                <el-input @input="select" v-model="searchDeptName" placeholder="请输入部门名称"></el-input>
            </el-form-item>
        </el-form>
        <!-- 表格 -->
        <el-table :data="depts" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection"></el-table-column>
            <el-table-column prop="deptID" label="部门编号"></el-table-column>
            <el-table-column prop="deptName" label="部门名称"></el-table-column>
            <el-table-column prop="remark" label="部门描述"></el-table-column>
            <el-table-column prop="lastTime" label="上次时间">
                <template #default="{ row }">
                    {{ row.lastTime | DataTime }}
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
                <template #default="{ row }">
                    <el-button type="warning" plain @click="Upd(row)" size="small">修改</el-button>
                    <el-popconfirm confirm-button-text='确定' cancel-button-text='不用了' icon="el-icon-info"
                        icon-color="red" title="确实删除此部门吗？" @confirm="del(row.deptID)">
                        <el-button type="danger" plain slot="reference" size="small">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination style="margin-top: 15px;" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="page" :page-size="size" :page-sizes="[5, 10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper" :total="count">
        </el-pagination>
        
        <el-dialog title="添加部门" append-to-body :visible.sync="AddDialogVisible" width="700px">
            <AddDept v-model="AddDialogVisible" @refresh="select"></AddDept>
        </el-dialog>

        <el-dialog title="修改部门" append-to-body :visible.sync="UpdDialogVisible" width="700px">
            <UpdDept v-model="UpdDialogVisible" :data="user" @refresh="select"></UpdDept>
        </el-dialog>

    </div>
</template>
<script>
import AddDept from './Add.vue'
import UpdDept from './Upd.vue'

export default {
    name: "Index",
    data() {
        return {
            searchDeptName: '',
            depts: [], user: {},
            activeIndex: '1',
            AddDialogVisible: false, UpdDialogVisible: false,
            count: 0, size: 10, page: 1,
            multipleSelection: []
        }
    },
    created() {
        this.select();
    },
    filters: {
        DataTime(value) {
            // 分割日期和时间部分
            const [datePart, timePart] = value.split('T');
            const [year, month, day] = datePart.split('-');
            const [hours, minutes, secondsWithMs] = timePart.split(':');
            const seconds = secondsWithMs.split('.')[0]; // 去除毫秒部分

            // 直接拼接结果（无需补零，原字符串已补零）
            const result = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            return result;
        }
    },
    methods: {
        //搜索
        select() {
            this.axios({
                method: 'get',
                url: 'Dept/GetDeptByPage',
                params: { page: this.page, limit: this.size, name: this.searchDeptName },
                headers: { Authorization: sessionStorage.getItem('token') }
            }).then(res => {
                console.log('res: ', res.data);
                this.depts = res.data.data;
                this.count = res.data.count;
            }).catch(err => {
                console.log('err: ', err);
            })
        },
        //删除
        del(did) {
            this.axios({
                method: 'Delete',
                url: 'Department',
                params: { id: did },
                headers: {
                    Authorization: sessionStorage.getItem('token'),
                    'Content-Type': 'application/json'
                }
            }).then(res => {
                if (res.data.code>0) {
                    this.$notify({
                        title: '成功',
                        message: res.data.msg,
                        type: 'success'
                    });
                } else {
                    this.$notify.error({
                        title: '错误',
                        message: res.data.msg
                    });
                }
                console.log('res: ', res);
                this.select();
            }).catch(err => {
                console.log('err: ', err);
            })
        },
        //批量删除
        delDetp() {
            let ids = [];
            ids = this.multipleSelection.map(v => v.deptID);
            if (ids.length > 0) {
                this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.axios({
                        method: 'Delete',
                        url: 'Department',
                        data: ids,
                        headers: {
                            Authorization: sessionStorage.getItem('token'),
                            'Content-Type': 'application/json'
                        }
                    }).then(res => {
                        if (res.data.code>0) {
                            this.$notify({
                                title: '成功',
                                message: res.data.msg,
                                type: 'success'
                            });
                        } else {
                            this.$notify.error({
                                title: '错误',
                                message: res.data.msg
                            });
                        }
                            this.page = 1;
                            this.select();
                    }).catch(err => {
                        console.log('err: ', err);
                    })

                }).catch(() => {
                    this.$notify({
                        title: '提示',
                        message: this.$createElement('i', { style: 'color: teal' }, '已取消删除')
                    });
                });
            } else {
                this.$notify({
                    title: '提示',
                    message: this.$createElement('i', { style: 'color: teal' }, '请选择需要删除的数据！')
                });
            }
        },
        //添加
        Add() {
            this.AddDialogVisible = true;
        },
        //修改
        Upd(e) {
            this.user = e;
            this.UpdDialogVisible = true;
        },
        //切换每页条数      
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.page = 1;
            this.size = val;
            this.select();
        },
        //翻页
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.page = val;
            this.select();
        },
        //获取选中的复选框数据id
        handleSelectionChange(val) {
            this.multipleSelection = val;
        }
    },
    components: {
        AddDept, UpdDept
    }
}
</script>
<style scoped>
button {
    margin: 5px;
}
</style> 